package ilender.controller;

import lombok.*;

import com.google.gson.*;

import ilender.annotations.*;
import ilender.dispatching.ControllerTools;
import ilender.mappers.*;
import ilender.models.*;
import ilender.util.*;

/**
 * @see Controller
 */
@Controller("navigation")
public class NavigationController{
	/**
	 * Loads the initial panels.
	 *
	 * If fbref is "MOffer" or "MItem", followed by '#' and then an ID,
	 * automatically opens the offer or item with that ID(by setting
	 * `openDialogFromResponse` in the response object).
	 *
	 * @param request <pre>
	 * {
	 *     fbref:(the reference from the link that brought the user here)
	 * }
	 * </pre>
	 *
	 * @return <pre>
	 * {
	 *     ejs:(the initial EJS to load),
	 *     openDialogFromResponse:(object containing details for opening a dialog)
	 * }
	 * </pre>
	 */
	public static JsonElement home(JsonObject request,ControllerTools tools){
		JsonObject callFunctions=new JsonObject();
		if(null!=request.get("fbref")){
			String[] fbrefParts=request.get("fbref").getAsString().split("#");
			Long modelId=Long.parseLong(fbrefParts[1]);
			switch(fbrefParts[0]){
				case "MOffer":
					val userPanelJson=userPanel(JsonTools.makeObject("form_data",JsonTools.makeObject()),tools);
					userPanelJson.getAsJsonObject().addProperty("focus_on_offer_id",modelId);
					callFunctions.add("openDialogFromResponse",userPanelJson);
					break;
				case "MItem":
					val itemJson=ItemsController.fetchSingleCardlet(tools,modelId);
					itemJson.add("title",itemJson.get("name"));
					callFunctions.add("openDialogFromResponse",itemJson);
					break;
			}
		}

		StatisticsMapper statisticsMapper=tools.session.getMapper(StatisticsMapper.class);

		return JsonTools.makeObject(
				"ejs","home/homescreen",
				"callFunctions",callFunctions,
				"lends_statistics",statisticsMapper.lendsStatistics()
				);
	}

	/**
	 * The user panel.
	 *
	 * @return <pre>
	 * {
	 *     ejs:(the panel's ejs),
	 *     title:(the title of the panel dialog),
	 *     target_dialog:(a dialog to replace if currently open),
	 *     refresh_action:(this action - used to refresh the dialog if needed),
	 *     offers:(list of relevant offers),
	 *     username:(the name of the current user)
	 * }
	 * </pre>
	 */
	public static JsonElement userPanel(JsonObject request,ControllerTools tools){
		return JsonTools.makeObject(
				"ejs","user/user_panel",
				"title","User Panel",
				"target_dialog","user-panel-dialog",
				"refresh_action","navigation#userPanel",
				"offers",OffersController.fetchCardlets(tools),
				"username",tools.mUser.getName()
				);
	}
}

